﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xss.Data.Common.SessionStore;
using Xss.Data.Mapper;

namespace Xss.Data
{
    public class AdoRequest : IAdoRequest
    {
        public AdoRequest()
        {
            _extendProperies = new System.Collections.Hashtable();
        }

        public bool EnableTransaction
        {
            get;
            set;
        }

        public bool EnableAutoClose
        {
            get;
            set;
        }

        private System.Collections.IDictionary _extendProperies;
        public System.Collections.IDictionary ExtendProperies
        {
            get { return _extendProperies; }
        }

        public ISessionStore Store
        {
            get;
            set;
        }

        IAdoMapper _mapper;
        public IAdoMapper Mapper
        {
            get { return _mapper; }
            set { _mapper = value; _mapper.Request = this; }
        }

        /// <summary>
        /// 执行查询
        /// </summary>
        /// <param name="session"></param>
        public IAdoResponse Execute()
        {
            var key = CreateRequestKey();
            IAdoSession adoSession = Store.CurrentSession;
            if (adoSession == null)
            {
                Store.Store(adoSession = new AdoSession(this));
            }
            adoSession.OpenSession();
            adoSession.Close();

            return adoSession.Response;
        }

        /// <summary>
        /// 释放
        /// </summary>
        public void Dispose()
        {
            _extendProperies = null;
            Store.Release();
            Store = null;
            Mapper = null;
        }

        /// <summary>
        /// 创建关键字用于重复使用AdoSession
        /// </summary>
        /// <returns></returns>
        protected virtual string CreateRequestKey()
        {
            var defaultKey = "_DEFAULT_SESSION_";
            if (ExtendProperies.Contains("SESSIONID"))
            {
                defaultKey = ExtendProperies["SESSIONID"].ToString();
            }

            Store = SessionStore.GetSessionStore(defaultKey);
            return defaultKey;
        }


        public string DataSource
        {
            get;
            set;
        }
    }
}
